package com.caiyi.financial.nirvana.sms.scheduled;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.gateway.Controller;
import com.caiyi.financial.nirvana.sms.gateway.DefaultGateWay;
import com.caiyi.financial.nirvana.sms.gateway.GateWayThread;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.AlarmSendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class QueryBalanceTask {

    private static final Logger logger = LoggerFactory.getLogger(QueryBalanceTask.class);

    /**
     * 每5分钟执行一次
     * 查询各通道余额
     */
    @Scheduled(fixedRate = Constant.TEN_MINUTES_OF_SECOND * 1000 / 2, initialDelay = Constant.TEN_MINUTES_OF_SECOND * 1000 / 2)
    public void queryBalance() {
        String lockKey = String.format(JedisKey.SMS_SCHEDULED_KEY_METHOD, "queryBalanceSchedule ", "queryBalance");
        boolean status = CommUtil.checkStatus(lockKey, Constant.TEN_MINUTES_OF_SECOND / 10);
        if (status) {
            Collection<GateWayThread<? extends DefaultGateWay>> gateWayThreads = Controller.getCurrentGateWay().values();
            for (GateWayThread gateWayThread : gateWayThreads) {
                DefaultGateWay defaultGateWay = gateWayThread.getGateWay();
                try {
                    if (defaultGateWay != null) {
                        int balance = defaultGateWay.queryBalance();
                        JedisService.hset(JedisKey.SMS_GATEWAY_BALANCE, defaultGateWay.info.getId() + "", balance + "");
                        logger.info("QueryBalanceTask 通道：{} 剩余短信余额为：{}", defaultGateWay.info.getName(), balance);
                    }
                } catch (NoSuchMethodException e) {
                    logger.info("QueryBalanceTask: {}未实现余额查询方法", defaultGateWay.info.getName());
                } catch (Exception e) {
                    logger.error("QueryBalanceTask Error !", e);
                }
            }
        }
    }

    /**
     * 发送报警短信
     *
     * @param phone   电话号码
     * @param content 内容
     */
    private boolean sendAlarmMessage(String phone, String content) {
        if (StringUtils.isBlank(phone)) {
            logger.info("报警号码为空，无法发送内容 : {} ", content);
            return false;
        }
        AlarmSendQueueEntity entity = new AlarmSendQueueEntity();
        entity.setPhone(phone);
        entity.setContent(content);
        JedisService.lpush(JedisKey.SMS_QUEUE_ALARM_MSG_SEND, JSON.toJSONString(entity));
        logger.info("报警短信已发送至{}，发送内容 : {} ", phone, content);
        return true;
    }
}
